package com.example.demo_mysql_mybatisplus.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SpringContextUtil implements ApplicationContextAware {
    /** 上下文对象实例 */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过class获取feignBean
     */
//    public static <T> T getFeign( Class<T> clas) {
//        FeignContext feignContext = applicationContext.getBean("feignContext", FeignContext.class);
//        return feignContext.getInstance( clas.getAnnotation(FeignClient.class).name() , clas );
//    }


    /**
     * 通过name,以及Clazz返回指定的Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 创建 bean
     */
    public static <T> void registerBean(String beanName, T bean) {
        // 将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) getApplicationContext();
        // 将bean对象注册到bean工厂
        context.getBeanFactory().registerSingleton(beanName, bean);
        log.debug("【SpringContextUtil】注册实例“" + beanName + "”到spring容器：" + bean);
    }
}
